﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace PrinterMasterServer
{
    class FileRecv
    {
        public static FileRecv m_this = new FileRecv();
        public static FileRecv getInstance() { return m_this; }
        public static int port = 520;
        private const int BufferSize = 1024;
        public static IPEndPoint ip;//= new IPEndPoint("", port);
        public static string path = System.AppDomain.CurrentDomain.BaseDirectory + "Files";
        public FileRecv()
        {
            byte[] i = new byte[4];
            i[0] = 127;
            i[1] = 0;
            i[2] = 0;
            i[3] = 1;
            ip = new IPEndPoint(IPAddress.Parse("192.168.0.254"), 5555);
        }
        private static System.Diagnostics.Stopwatch sw;
        /// <summary>
        /// 开始监控端口直到有文件传输请求.
        /// </summary>
        public void stratPort()
        {

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Bind(ip);
            sock.Listen(1);
            while (true)
            {
                try
                {
                    Console.WriteLine(Log.Write(Log.Type.debug, Log.Titel.debug信息, "开始监听端口"));
                    Socket client = sock.Accept();
                    Console.WriteLine(Log.Write(Log.Type.debug, Log.Titel.debug信息, "有数据传入"));
                    byte[] buffer = new byte[BufferSize];
                    client.Receive(buffer);
                    long receive = 0L, length = BitConverter.ToInt64(buffer, 0);
                    
                    string fileName = Encoding.Default.GetString(buffer, 0, client.Receive(buffer));
                    Console.WriteLine(Log.Write(Log.Type.debug, Log.Titel.debug信息, "文件名:"+fileName));
                    //Console.WriteLine("Receiveing file:" + fileName + ".Plz wait...");
                    using (FileStream writer = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        int received;
                        while (receive < length)
                        {
                            sw = new System.Diagnostics.Stopwatch();
                            received = client.Receive(buffer);
                            writer.Write(buffer, 0, received);
                            writer.Flush();
                            receive += (long)received;
                            
                            Console.WriteLine("传输百分比:" + ((double)receive / (double)length * 100).ToString("0.00") + "%");
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex.Message); }

            }

            // }
        }
        /// <summary>
        /// 结束监控端口
        /// </summary>
        public void exitProt()
        {
        }
    }
}
